import 'package:demo_proj01/repository/datas/home_list_data.dart';
import 'package:demo_proj01/pages/homeviewmodel.dart';
import 'package:demo_proj01/route/routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class Homepage extends StatefulWidget {
  const Homepage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<Homepage> {
  List<Color> myColors = [Colors.blue, Colors.black, Colors.lime];
  HomeViewModel viewModel = HomeViewModel();
  RefreshController refreshController = RefreshController();

  @override
  void initState() {
    super.initState();
    viewModel.getBannerList();
    viewModel.getHomeList(false);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        body: SafeArea(
          child: SmartRefresher(
            controller: refreshController,
            enablePullUp: true,
            enablePullDown: true,
            header: ClassicHeader(),
            footer: ClassicFooter(),
            onLoading: () {
              // 上拉加载回调
              viewModel.getHomeList(true).then((onValue) {
                refreshController.loadComplete();
              });
            },
            onRefresh: () {
              // 下拉刷新回调
              viewModel.getBannerList().then((onValue) {
                viewModel.getHomeList(false).then((onValue) {
                  refreshController.refreshCompleted();
                });
              });
            },
            child: SingleChildScrollView(
              child: Column(children: <Widget>[_banner(), _homeListView()]),
            ),
          ),
        ),
      ),
    );
  }

  Widget _homeListView() {
    return Consumer<HomeViewModel>(
      builder: (context, vm, child) {
        return ListView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return _listItemView(vm.homeList?.elementAt(index));
          },
          itemCount: vm.homeList?.length ?? 0,
        );
      },
    );
  }

  Widget _banner() {
    return Consumer<HomeViewModel>(
      builder: (context, vm, child) {
        return SizedBox(
          height: 200,
          width: double.infinity,
          child: Swiper(
            itemCount: vm.bannerList?.length ?? 0,
            itemBuilder: (context, index) {
              return Container(
                margin: EdgeInsets.all(15),
                height: 100,
                color: myColors.elementAt(index % 3),
                child: Image.network(vm.bannerList?[index].imagePath ?? ""),
              );
            },
            indicatorLayout: PageIndicatorLayout.COLOR,
            autoplay: true,
          ),
        );
      },
    );
  }

  Widget _listItemView(HomeListItemData? itemData) {
    var name;
    if (itemData?.author?.isNotEmpty == true) {
      name = itemData?.author ?? "";
    } else {
      name = itemData?.shareUser ?? "";
    }
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, RoutePath.webViewPage);
      },
      child: Container(
        margin: EdgeInsets.only(top: 5, bottom: 5, left: 10, right: 10),
        padding: EdgeInsets.only(top: 5, bottom: 5, left: 10, right: 10),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black12, width: 0.5),
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Image.network(
                  "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202005%2F04%2F20200504162800_Fu5VV.thumb.400_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1759721470&t=2df256fee569b2defab4cf8d9a490b3a",
                  width: 30,
                  height: 30,
                  fit: BoxFit.fill,
                ),
                SizedBox(width: 5),
                Text(name, style: TextStyle(color: Colors.black)),
                Expanded(child: SizedBox()),
                Text(
                  itemData?.niceShareDate ?? "",
                  style: TextStyle(color: Colors.black, fontSize: 12),
                ),
                SizedBox(width: 5),
                Text(
                  "置顶",
                  style: TextStyle(
                    color: Colors.blue,
                    fontWeight: FontWeight.w600,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
            SizedBox(height: 5),
            Text(
              itemData?.title ?? "",
              style: TextStyle(color: Colors.black, fontSize: 14),
            ),
            Row(
              children: [
                Text(
                  itemData?.chapterName ?? "",
                  style: TextStyle(color: Colors.green, fontSize: 12),
                ),
                Expanded(child: SizedBox()),
                Image.asset(
                  "assets/images/collect-32.png",
                  width: 25,
                  height: 25,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
